package cn.study.feignclient.interceptor;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;

import java.io.IOException;
import java.util.*;

/**
 * FeignInterceptor ,再发送请求前，对RequestTemplate进行处理
 */
@Component
public class FeignGetRequestInterceptor implements RequestInterceptor {

    @Autowired
    ObjectMapper objectMapper;

    public void apply(RequestTemplate requestTemplate) {
        //如果是get请求，并且requestbody中包含pojo转换的json，那么就将他转换为body
        System.out.println(requestTemplate.body());
        if(requestTemplate.method().equals("GET") && requestTemplate.body() !=null){
            try {
                System.out.println(requestTemplate.body());
                JsonNode jsonNode = objectMapper.readTree(requestTemplate.body());
                requestTemplate.body(null);
                Map<String, Collection<String>> queries = new HashMap<>();
                buildQuery(jsonNode,queries);
                requestTemplate.queries(queries);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //将JsonNode递归形成一个RequestTemplate支持的Query
    public void buildQuery(JsonNode jsonNode,Map<String,Collection<String>> queries){
        Iterator<Map.Entry<String, JsonNode>> fields = jsonNode.fields();
        while (fields.hasNext()) {
            Map.Entry<String, JsonNode> next =  fields.next();
            if(!next.getValue().fields().hasNext()){
                //如果为null就不在放了，不然传参会传 null 字符串
                if ( next.getValue().asText().equals("null")){
                    continue;
                }
                List<String> values = new ArrayList<>();
                values.add(next.getValue().asText());
                queries.put(next.getKey(), values);
            }else{
                buildQuery(fields.next().getValue(),queries);
            }
        }
    }

}
